<template>
  <div class="app-container">
    <a-title @clickPreview="preview" />
    <div class="input-wrap">
      <div class="input-label">当前代理人</div>
      <div class="input-content">
        <el-select
          v-model="adminList"
          multiple
          placeholder="请选择"
          @change="changevalue"
          :filterable="true"
        >
          <el-option
            v-for="item in options"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          ></el-option>
        </el-select>
        <el-tag class="tipTag">
          <i class="el-icon-warning" /> 请直接下拉选择或取消代理人授权
        </el-tag>
      </div>
    </div>
    <div class="history">代理人变更历史记录</div>

    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="getHistoryList"
        />
      </el-form-item>
      <el-form-item label="变更内容" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入变更内容"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="getHistoryList"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getHistoryList"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      stripe
      :data="tableData"
      v-loading="loading"
      @sort-change="tableSortChangeHistory"
      :default-sort="{ prop: 'updateTime', order: 'descending' }"
    >
      <el-table-column
        label="时间"
        prop="updateTime"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="姓名"
        prop="nickName"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      ></el-table-column>
      <el-table-column
        label="手机号码"
        prop="phonenumber"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      ></el-table-column>
      <el-table-column
        label="员工编号"
        prop="jobNo"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      ></el-table-column>
      <el-table-column
        label="变更内容"
        prop="remark"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      ></el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getHistoryList"
    />
  </div>
</template>

<script>
import {
  listWorkflowAgencyHistory,
  getWorkflowAgencyHistory,
  delWorkflowAgencyHistory,
  addWorkflowAgencyHistory,
  updateWorkflowAgencyHistory,
  exportWorkflowAgencyHistory,
  cancleAgency,
} from "@/api/projectleader/workflowAgencyHistory";
import {
  adminAuthorizeList,
  agencyList,
  adminAuthorizeHistoryList,
  cancelAdminAuthorize,
  addAdminAuthorize,
} from "@/api/projectleader/adminAuthorize";
import aTitle from "@/components/Title";
export default {
  name: "WorkflowAgencyHistory",
  components: { aTitle },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      adminList: [],
      // 非单个禁用
      single: true,
      tableData: [],
      // 非多个禁用
      multiple: true,
      options: [],
      // 总条数
      total: 0,
      // 项目负责人委托历史变更记录 表格数据
      workflowAgencyHistoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        leader: undefined,
        remark:undefined,
        nickName:undefined
      },
      // 表单参数
      form: [],
      // 表单校验
      rules: {},
      userinfo: null,
    };
  },
  created() {
    this.getList();
    this.getHistoryList();
  },
  mounted() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userinfo") || {}).userId;
  },
  methods: {
    preview() {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}项目负责人工作台/业务系统操作说明-项目负责人工作台-管理员授权.xlsx`
      )}&name=${encodeURIComponent(
        "业务系统操作说明-项目负责人工作台-管理员授权.xlsx"
      )}`;
    },
    /** 查询项目负责人委托历史变更记录 列表 */
    getList() {
      debugger;
      agencyList({ leader: this.$route.params.id }).then((res) => {
        this.options = res.data;
        res.data
          .filter((item) => item.agencyFlag === "1")
          .map((item) => {
            this.adminList.push(item.userId);
            this.form.push(item.userId);
          });
      });
    },
    getHistoryList() {
      this.loading = true;
      this.queryParams.leader=this.$route.params.id;
      listWorkflowAgencyHistory(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        guid: undefined,
        userId: undefined,
        leader: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getHistoryList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.guid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目负责人委托历史变更记录 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const guid = row.guid || this.ids;
      getWorkflowAgencyHistory(guid).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目负责人委托历史变更记录 ";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.guid != undefined) {
            updateWorkflowAgencyHistory(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getHistoryList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addWorkflowAgencyHistory(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getHistoryList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guids = row.guid || this.ids;
      this.$confirm(
        '是否确认删除项目负责人委托历史变更记录 编号为"' + guids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delWorkflowAgencyHistory(guids);
        })
        .then(() => {
          this.getHistoryList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm(
        "是否确认导出所有项目负责人委托历史变更记录 数据项?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return exportWorkflowAgencyHistory(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    changevalue(val) {
      debugger;
      let a = new Set(this.form);
      let b = new Set(val);
      if (val && val.length > 1) {
        console.log(this.adminList);
        let arr = Array.from(new Set([...a].filter((x) => !b.has(x))));
        this.adminList=[];
        this.adminList.push(val[0]);
        this.msgError("只能选择一个代理人，请清除代理人后，重新选择！");
      } else {
        if (this.form.length > val.length) {
          let arr = Array.from(new Set([...a].filter((x) => !b.has(x))));
          let list = {
            leader: this.userinfo,
            userId: arr[0],
            guid: this.options.filter((item) => item.userId === arr[0])[0].guid,
          };
          this.$confirm("确认取消该用户授权代理?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              return cancleAgency(list).then((res) => {
                this.form = val;
                this.getHistoryList();
              });
            })
            .catch(() => {
              this.adminList.push(arr[0]);
            });
        } else {
          let arr = Array.from(new Set([...b].filter((x) => !a.has(x))));
          let list = {
            leader: this.userinfo,
            userId: arr[0],
            guid: this.options.filter((item) => item.userId === arr[0])[0].guid,
          };
          this.$confirm("确认给该用户授权代理?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              return addWorkflowAgencyHistory(list).then((res) => {
                if (res.code === 200) {
                  this.form = val;
                  this.getHistoryList();
                }
              });
            })
            .catch(() => {
              this.adminList = this.adminList.filter((item) => item != arr[0]);
            });
        }
      }
    },
    tableSortChangeHistory(column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getHistoryList();
    },
  },
};
</script>
<style lang="scss" scoped>
.input-wrap {
  padding: 8px;
  display: flex;

  .input-label {
    min-width: 1em;
    max-width: 6em;
    color: rgba(0, 0, 0, 0.65);
    margin-right: 8px;
    display: flex;
    align-items: center;
    flex: 0 0 90px;
  }

  .input-content {
    -webkit-box-flex: 1;
    flex-grow: 1;
    .el-select {
      width: 30%;
    }
  }
}
.history {
  margin-top: 60px;
  margin-bottom: 20px;
  padding: 20px 8px;
  border-top: 1px solid #dfe6ec;
  color: rgba(0, 0, 0, 0.65);
}
/deep/.el-tag.el-tag--info {
  background-color: #1890ff;
  border-color: #e9e9eb;
  color: #ffffff;
  font-size: 16px;
}
.tipTag {
  margin-left: 20px;
  height: 40px;
  line-height: 40px;
}
</style>